package com.he.eduservice.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.util.BeanUtil;
import com.he.eduservice.entity.EduSubject;
import com.he.eduservice.entity.EduTeacher;
import com.he.eduservice.entity.excel.SubjectData;
import com.he.eduservice.entity.subject.OneSubject;
import com.he.eduservice.entity.subject.TwoSubject;
import com.he.eduservice.listener.SubjectExeclListener;
import com.he.eduservice.mapper.EduSubjectMapper;
import com.he.eduservice.service.EduSubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author testhejinyu
 * @since 2021-05-31
 */
@Service
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    //添加课程分类
    @Override
    public void saveSubject(MultipartFile file) {
        try {
            InputStream in = file.getInputStream();
            EasyExcel.read(in, SubjectData.class, new SubjectExeclListener()).sheet().doRead();
        } catch (Exception e) {

        }
    }

    @Override
    public List<OneSubject> getAllSubject() {
        //1.一级分类
        QueryWrapper queryWrapperOne = new QueryWrapper();
        queryWrapperOne.eq("parent_id", "0");
        List<EduSubject> oneSubjectList = baseMapper.selectList(queryWrapperOne);
        //2.二级分类
        QueryWrapper queryWrapperTwo = new QueryWrapper();
        queryWrapperTwo.ne("parent_id", "0");
        List<EduSubject> twoSubjectList = baseMapper.selectList(queryWrapperTwo);

        List<OneSubject> list = new ArrayList<>();
        for (int i = 0; i < oneSubjectList.size(); i++) {
            EduSubject eduSubject = oneSubjectList.get(i);
            OneSubject oneSubject = new OneSubject();

            //eduSubject 值复制到 oneSubject
            BeanUtils.copyProperties(eduSubject, oneSubject);
            list.add(oneSubject);

            List<TwoSubject> twoSubjects = new ArrayList<>();
            for (int j = 0; j < twoSubjectList.size(); j++) {
                EduSubject currentTwoSubject = twoSubjectList.get(j);
                if(currentTwoSubject.getParentId().equals(oneSubject.getId())){
                    TwoSubject twoSubject = new TwoSubject();
                    BeanUtils.copyProperties(currentTwoSubject,twoSubject);
                    twoSubjects.add(twoSubject);
                }
            }
            //把当前一级下面的二级分类放上去
            oneSubject.setChildren(twoSubjects);

        }
        return list;
    }
}
